package com.tlgen.controller;

import com.alibaba.fastjson.JSONObject;
import com.tlgen.domain.ColumnVO;
import com.tlgen.domain.ReceiveVO;
import com.tlgen.utils.GenerateUtils;
import com.tlgen.utils.ZipUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.io.*;
import java.util.*;
import static com.tlgen.utils.GenerateUtils.*;

@RestController
public class HelloController {

    // 基本文件路径
    private static final String FILE_PREFIX = "E:/generate/";

    @Autowired
    private GenerateUtils generateUtils;

    /**
     * 将 JSON 生成 VO 对象
     * @param receive
     * @return
     * @throws IOException
     */
    @PostMapping("/generator")
    public ResponseEntity<byte[]> generator(@RequestBody ReceiveVO receive) throws IOException {

        String uuid = UUID.randomUUID().toString();

        // 获取合适 (当一个数组中包含多个对象, 取出包含属性个数最多的对象进行生成) 的 JSONObject 对象
        JSONObject jsonObject = getMaxLengthJSONObject(receive.getJson());

        // 构造生成模板参数
        List<ColumnVO> voList = getColumnList(jsonObject);
        ColumnVO vo = new ColumnVO();
        vo.setPackageName(receive.getPackageName());
        vo.setClassName(receive.getClassName());
        vo.setClassExtendName(receive.getExtendName());
        vo.setColumnList(voList);

        // 第一层生成
        generateUtils.generateCode(vo, getPath(uuid));

        // 嵌套生成
        iteratorGenerator(jsonObject, getPath(uuid), receive.getClassName(), receive.getPackageName());

        // 生成压缩包
        ZipUtils.generatorZip(getPath(uuid), FILE_PREFIX + uuid + ".zip");

        // 下载压缩包
        File file = new File(FILE_PREFIX + uuid + ".zip");
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment",  uuid + ".zip");
        // 删除临时文件
        file.deleteOnExit();
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);

    }

    /**
     * 创建文件夹, 获取路径
     * @param uuid
     * @return
     */
    public static String getPath(String uuid) {
        String path = FILE_PREFIX + uuid + "/";
        File newFile = new File(path);
        if (!newFile.exists()) {
            newFile.mkdirs();
        }
        return path;
    }


}
